import React, {Fragment, useEffect, useState} from 'react';
import {Avatar, Badge, Button, Card, Dropdown, Icon, List, Menu, Table, Divider, message, Popconfirm, Tooltip} from 'antd';
import {PageHeaderWrapper} from '@ant-design/pro-layout';
import styles from '@/utils/table.less';
import {connect} from 'dva';
import {ConnectState, Dispatch} from '@/models/connect';
import encodeQueryParam from '@/utils/encodeParam';
import apis from '@/services';
import SearchForm from '@/components/SearchForm';
import {RuleInstanceItem} from './data.d';
import Save from './save';
import Detail from './save/detail';
import SqlRuleSave from '@/pages/rule-engine/sqlRule/save/index';
import cardStyles from "@/pages/device/product/index.less";
import DeviceAlarm from "@/pages/rule-engine/control/img/DeviceAlarm.png";
import NodeRed from "@/pages/rule-engine/control/img/NodeRed.png";
import SqlServer from "@/pages/rule-engine/control/img/SqlServer.png";
import AutoHide from "@/pages/device/location/info/autoHide";
import AlarmSave from "@/pages/device/alarm/save/index";
import moment from 'moment';

interface Props {
  ruleInstance: any;
  dispatch: Dispatch;
  location: Location;
  loading: boolean;
}

interface State {
  data: any;
  searchParam: any;
  saveVisible: boolean;
  detailVisible: boolean,
  current: Partial<RuleInstanceItem>;
  deviceAlarm: any;
  deviceMateData: string;
  detailData: any;
}

const RuleInstanceList: React.FC<Props> = props => {
  const {dispatch} = props;

  const {result} = props.ruleInstance;

  const initState: State = {
    data: result,
    searchParam: {
      pageSize: 10,terms: { modelType: 'node-red' }, sorts: {
        order: "descend",
        field: "createTime"
      }
    },
    saveVisible: false,
    detailVisible: false,
    current: {},
    deviceAlarm: {},
    deviceMateData: "",
    detailData: {},
  };

  const [searchParam, setSearchParam] = useState(initState.searchParam);
  const [saveVisible, setSaveVisible] = useState(initState.saveVisible);
  const [detailVisible, setDetailVisible] = useState(initState.detailVisible);
  const [detailData, setDetailData] = useState(initState.detailData);
  const [saveSqlRuleVisible, setSaveSqlRuleVisible] = useState(false);
  const [saveAlarmVisible, setSaveAlarmVisible] = useState(false);
  const [current, setCurrent] = useState(initState.current);
  const [ruleData, setRuleData] = useState(initState.current);
  const [deviceAlarm, setDeviceAlarm] = useState(initState.deviceAlarm);
  const [deviceMateData, setDeviceMateData] = useState(initState.deviceMateData);

  const modelType = new Map();
  modelType.set('device_alarm', '设备告警');
  modelType.set('sql_rule', '数据转发');
  modelType.set('node-red', '规则引擎');
  modelType.set('rule-scene', '场景联动');

  const handleSearch = (params?: any) => {
    setSearchParam(params);
    dispatch({
      type: 'ruleInstance/query',
      payload: encodeQueryParam(params),
    });
  };

  useEffect(() => {
    handleSearch(searchParam);
  }, []);

  const startInstance = (record: any) => {
    apis.ruleInstance
      .start(record.id)
      .then(response => {
        if (response.status === 200) {
          message.success('启动成功');
          handleSearch(searchParam);
        }
      })
      .catch(() => {
      });
  };

  const stopInstance = (record: any) => {
    apis.ruleInstance
      .stop(record.id)
      .then(response => {
        if (response.status === 200) {
          message.success('停止成功');
          handleSearch(searchParam);
        }
      })
      .catch(() => {
      });
  };

  const handleDelete = (params: any) => {
    dispatch({
      type: 'ruleInstance/remove',
      payload: params.id,
      callback: () => {
        message.success('删除成功');
        handleSearch(searchParam);
      },
    });
  };

  const onChange = (page: number, pageSize: number) => {
    handleSearch({
      pageIndex: page - 1,
      pageSize,
      terms: searchParam.terms,
      sorts: searchParam.sorts,
    });
  };

  const onShowSizeChange = (current: number, size: number) => {
    handleSearch({
      pageIndex: current - 1,
      pageSize: size,
      terms: searchParam.terms,
      sorts: searchParam.sorts,
    });
  };

  const saveOrUpdate = (item: RuleInstanceItem) => {
    apis.sqlRule.saveOrUpdate(item)
      .then((response: any) => {
        if (response.status === 200) {
          message.success('保存成功');
          setSaveSqlRuleVisible(false);
          setCurrent({});
          handleSearch(searchParam);
        }
      })
      .catch(() => {
      });
  };

  const updateDeviceAlarm = (item: any) => {
    let data: any;
    try {
      data = JSON.parse(item.modelMeta);
    } catch (error) {
      message.error("数据结构异常");
      return;
    }
    if (data.target === 'product') {
      apis.deviceProdcut.info(data.targetId)
        .then((response: any) => {
          if (response.status === 200 && response.result) {
            setDeviceMateData(response.result.metadata);
            setDeviceAlarm(data);
            setSaveAlarmVisible(true);
          } else {
            message.error("告警相关产品不存在。");
          }
        })
        .catch(() => {
        })
    } else {
      apis.deviceInstance.info(data.targetId)
        .then((response: any) => {
          if (response.status === 200 && response.result) {
            setDeviceMateData(response.result.metadata);
            setDeviceAlarm(data);
            setSaveAlarmVisible(true);
          } else {
            message.error("告警相关设备不存在。");
          }
        })
        .catch(() => {
        })
    }
  };

  const submitData = (data: any) => {
    apis.deviceAlarm.saveProductAlarms(deviceAlarm.target, deviceAlarm.targetId, data)
      .then((response: any) => {
        if (response.status === 200) {
          message.success('保存成功');
          setSaveAlarmVisible(false);
          handleSearch(searchParam);
        }
      })
      .catch(() => {
      });
  };

  const cardInfoTitle = {
    fontSize: 14,
    color: 'rgba(0, 0, 0, 0.85)'
  };

  const onTableChange = (
    pagination: PaginationConfig,
    filters: any,
    sorter: SorterResult<RuleInstanceItem>,
  ) => {
    handleSearch({
      pageIndex: Number(pagination.current) - 1,
      pageSize: pagination.pageSize,
      terms: searchParam,
      sorts: sorter,
    });
  };

  const statusMap = new Map();
  statusMap.set('已启动', 'success');
  statusMap.set('已停止', 'error');
  statusMap.set('已禁用', 'processing');

  const columns: ColumnProps<RuleInstanceItem>[] = [
    {
      title: 'ID',
      dataIndex: 'id',
    },

    {
      title: '名称',
      dataIndex: 'name',
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      defaultSortOrder: 'descend',
      render: (text: any) => text ? moment(text).format('YYYY-MM-DD HH:mm:ss') : '/',
    },
    {
      title: '状态',
      dataIndex: 'state',
      render: record => record ? <Badge status={statusMap.get(record.text)} text={record.text} /> : '',
    },
    {
      title: '操作',
      width: '25%',
      render: (text, record) => (
        <Fragment>
          <a onClick={() => {window.open(`/AllLinks/rule-editor/index.html#flow/${record.id}`)}}>编辑</a>
          <Divider type="vertical" />
          <Popconfirm
            placement="topRight"
            title={record.state?.value === 'stopped' ? '确认启动？' : '确认停止？'}
            onConfirm={() => {
              if (record.state?.value === 'stopped') {
                startInstance(record);
              } else {
                stopInstance(record);
              }
            }}
          >
            <a>{record.state?.value === 'stopped' ? '启动' : '停止'}</a>
          </Popconfirm>
          <Divider type="vertical" />
          <a onClick={() => {setRuleData(record);setSaveVisible(true);}}>复制</a>
          <Divider type="vertical" />
          <Popconfirm
            title="确定删除此组件吗？"
            onConfirm={() => {
              handleDelete(record);
            }}
          >
            <a>删除</a>
          </Popconfirm>
        </Fragment>
      ),
    },
  ];
  return (
    <PageHeaderWrapper title="联动控制">
      <Card bordered={false}>
        <div className={styles.tableList}>
          <div>
            <SearchForm
              formItems={[
                {
                  label: '名称',
                  key: 'name$LIKE',
                  type: 'string',
                },
                {
                  label: '状态',
                  key: 'state$IN',
                  type: 'list',
                  props: {
                    data: [
                      {id: 'stopped', name: '已停止'},
                      {id: 'started', name: '已启动'},
                      {id: 'disable', name: '已禁用'},
                    ]
                  }
                },
              ]}
              search={(params: any) => {
                // setSearchParam(params);
                let param = params;
                if (!param) param = {};
                param.modelType = 'node-red';
                handleSearch({
                  terms: param, pageSize: 8, sorts: searchParam.sorts || {
                    order: "descend",
                    field: "createTime"
                  }
                });
              }}
            />
          </div>
          <div className={styles.tableListOperator}>
            <Button
              // icon="plus"
              type="primary"
              onClick={() => {
                setSaveVisible(true)
              }}>
              新建
            </Button>
          </div>
        </div>
      </Card>
      <br/>
      <Card bordered={false}>
          <div className={styles.StandardTable}>
            <Table
              loading={props.loading}
              dataSource={(result || {}).data}
              columns={columns}
              rowKey="id"
              onChange={onTableChange}
              pagination={{
                current: result?.pageIndex + 1,
                total: result?.total,
                pageSize: result?.pageSize,
                showQuickJumper: true,
                showSizeChanger: true,
                pageSizeOptions: ['10', '20', '50', '100'],
                showTotal: (total: number) =>
                  `共 ${total} 条记录 第  ${result?.pageIndex + 1}/${Math.ceil(
                    result?.total / result?.pageSize,
                  )}页`,
              }}
            />
          </div>
      </Card>
      {saveVisible && (
        <Save
          data={ruleData}
          close={() => {
            setSaveVisible(false);
            setRuleData({});
            handleSearch(searchParam);
          }}
        />
      )}
      {detailVisible && (
        <Detail
          data={detailData}
          close={() => {
            setDetailVisible(false);
            setDetailData({});
          }}
        />
      )}
      {saveSqlRuleVisible && (
        <SqlRuleSave
          data={current}
          close={() => {
            setSaveSqlRuleVisible(false);
            setCurrent({});
          }}
          save={(item: RuleInstanceItem) => {
            saveOrUpdate(item);
          }}
        />
      )}
      {saveAlarmVisible && <AlarmSave
        close={() => {
          setDeviceAlarm({});
          setDeviceMateData("");
          setSaveAlarmVisible(false);
        }}
        save={(data: any) => {
          submitData(data);
        }}
        data={deviceAlarm} targetId={deviceAlarm.targetId}
        target={deviceAlarm.target} metaData={deviceMateData}
        name={deviceAlarm.name} productName={deviceAlarm.alarmRule.productName}
        productId={deviceAlarm.alarmRule.productId}
      />}
    </PageHeaderWrapper>
  );
};
export default connect(({ruleInstance, loading}: ConnectState) => ({
  ruleInstance,
  loading: loading.models.ruleInstance,
}))(RuleInstanceList);
